<template>
  <view class="pageLayout">
    <video
      v-if="videoDetail"
      id="videoPlayer"
      :src="videoDetail.videoUrl"
      :custom-cache="false"
      :current-time="currentTime"
      controls
      :autoplay="false"
      @play="startTimer"
      @pause="stopTimer"
      @timeupdate="handleTimeUpdate"
      @ended="handleVideoEnd"
      class="video-player"
    />
    <view class="progress-info">
      {{ videoDetail.title }}
    </view>
    <view class="videoTopic"
      >{{ videoDetail.topicName }}-{{ videoDetail.categoryName }}</view
    >
  </view>
</template>

<script>
import {
  queryVideoDetailByID,
  queryCurrentVideoWatchRecord,
  addWatchRecord,
} from "../api/businessVideo/index.js";
export default {
  data() {
    return {
      videoUrl: "", // 视频地址
      videoDuration: 0, // 视频总时长
      currentTime: 0, // 当前播放进度
      watchDuration: 0, // 观看时长
      timer: null, // 计时器
      vid: null, // 视频ID
      videoDetail: null, // 视频详情
      videoContext: null, // 视频上下文
      videoWatchRecord: {}, // 视频观看记录
      hasSeeked: false,
    };
  },
  onLoad(options) {
    // // 从路由参数获取视频ID和URL
    this.vid = options.id;
    this.getVideoDetail();
    // 初始化视频上下文
    this.videoContext = uni.createVideoContext("videoPlayer", this);
    console.log(this.videoContext, "videoContext");
    //
    // this.videoUrl = options.url;
    // this.storageKey = `video_progress_${this.vid}`;

    // // 加载本地进度
    // const savedProgress = uni.getStorageSync(this.storageKey);
    // if (savedProgress) {
    // 	this.currentTime = savedProgress.time;
    // 	this.watchDuration = savedProgress.duration;
    // }
  },
  methods: {
    // onVideoReady(e) {
    //   // 确保只执行一次跳转
    //   if (!this.hasSeeked && this.currentTime > 0) {
    //     this.hasSeeked = true;
    //     // 延时确保视频真正就绪
    //     setTimeout(() => {
    //       this.videoContext.seekTo(this.currentTime);
    //       console.log("跳转到上次播放时间:", this.currentTime);
    //     }, 500);
    //   }
    // },
    /**
     * 获取视频详情
     */
    async getVideoDetail() {
      try {
        let data = {
          videoID: this.vid,
        };
        let res = await queryVideoDetailByID(data);
        this.videoDetail = res.data;
        this.getVideoWatchRecord();
      } catch (e) {
        let message;
        if (e.data && e.data.detail) {
          message = e.data.detail;
        } else {
          message = e.errorMsg;
        }
        uni.showToast({
          title: message,
          icon: "none",
        });
      }
    },
    /**
     * 获取视频播放记录
     */
    async getVideoWatchRecord() {
      try {
        const res = await queryCurrentVideoWatchRecord({
          videoID: this.vid,
        });
        console.log(res.data.currentSecond, "getVideoWatchRecord");

        this.currentTime = res ? res.data.currentSecond : 0;
        console.log("currentTime", this.currentTime);
        this.videoContext.pause();
        this.videoContext.seek(this.currentTime);
        // this.setTimeout(() => {
        // }, 500);
      } catch (e) {
        let message;
        if (e.data && e.data.detail) {
          message = e.data.detail;
        } else {
          message = e.errorMsg;
        }
        uni.showToast({
          title: message,
          icon: "none",
        });
      }
    },
    // 开始播放
    startTimer() {
      this.timer = setInterval(() => {
        this.watchDuration++;
        if (this.watchDuration % 60 === 0) {
          this.uploadProgress();
        }
      }, 1000);
    },
    // 停止计时器
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
        this.uploadProgress();
      }
    },

    // 处理视频时间更新
    handleTimeUpdate(e) {
      // console.log(e, "handleTimeUpdate");
      this.currentTime = e.detail.currentTime.toFixed(0);
      this.videoDuration = e.detail.duration;
    },
    // 视频结束处理
    handleVideoEnd() {
      this.stopTimer();
      this.currentTime = this.videoDuration; // 标记为已看完
      this.uploadProgress();
    },
    // 上传观看记录
    async uploadProgress() {
      try {
        // console.log(this.currentTime);

        // let data = {
        //   videoId: this.videoDetail.videoID,
        //   topicID: this.videoDetail.topicID,
        //   topicName: this.videoDetail.topicName,
        //   categoryID: this.videoDetail.categoryID,
        //   categoryName: this.videoDetail.categoryName,
        //   title: this.videoDetail.title,
        //   second: this.watchDuration,
        //   currentSecond: Number(this.currentTime),
        // };
        // console.log(data);

        await addWatchRecord({
          videoId: this.videoDetail.videoID,
          topicID: this.videoDetail.topicID,
          topicName: this.videoDetail.topicName,
          categoryID: this.videoDetail.categoryID,
          categoryName: this.videoDetail.categoryName,
          title: this.videoDetail.title,
          second: this.watchDuration,
          currentSecond: Number(Number(this.currentTime).toFixed(0)),
        });
        // 清除本地记录
      } catch (err) {
        console.error("上传进度失败", err);
      }
    },
  },
  onHide() {
    // 新增功能：暂停视频 + 上传记录
    if (this.videoContext) {
      this.videoContext.pause(); // 暂停视频播放
    }
    this.stopTimer();
    // this.uploadProgress();
  },
  onUnload() {
    // 页面卸载时同样执行
    if (this.videoContext) {
      this.videoContext.pause();
    }
    this.stopTimer();
    // this.uploadProgress();
  },
};
</script>

<style lang="scss" scoped>
.video-player {
  width: 100%;
  height: 400rpx;
}
.progress-info {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
}
.videoTopic {
  font-size: 24rpx;
  color: #999999;
  margin-top: 18rpx;
}
</style>